import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Affix } from 'antd'
import { Carousel, Badge } from 'antd-mobile'
import { isFunc, PreLoad } from 'muka'
import { Button, Image, NavBar, Search, Grid } from 'components'
// import Slider from 'react-slick'
import { post } from '../../utils'
import './index.less'
import { TabBarView, ToTop } from '../../viewComponent'
// import BScroll from 'better-scroll'
export interface IClassfy {
    icon: string
    text: string
    id: number
}

// interface IState {
//     affixed: boolean
//     classfy: IClassfy[]
//     carousels: any[]
//     live: any
//     searchTop: number
//     searchWidth: number
//     searchLeft: number
// }

export default class Home extends Component<any, any> {

    public state = {
        affixed: false,
        // 轮播
        carousels: [],
        // gif轮
        hds: [],
        // 分类
        classfy: [],
        // 好货
        quality: {
            sale: {
                goods: []
            },
            new: []
        },
        // 精选
        choice: {
            act: {
                image: ''
            },
            goods: []
        },
        // 广告
        advert: [],
        // 人气
        popularity: [],
        // 新人
        newPeople: [],
        live: [],
        anmation: false,
        searchWidth: 0,
        searchLeft: 0,
        top: 0,
        val: 0,
        cartNum: 0,
        loading: false,
        divider: false,
        changeBtn: false
    }

    private timer: any

    private popularity: any

    public render(): JSX.Element {
        const { anmation, advert, carousels, live, quality, choice, popularity, hds, top, val, loading, divider, changeBtn, cartNum } = this.state
        return (
            <div className="home">
                <div
                    className="fixed"
                >
                    <NavBar
                        className={`home_nav`}
                        left={<img className="icon" src={anmation ? require('../../assets/msg_h.png') : require('../../assets/msg.png')} />}
                        title={<img className="logo" src={require('../../assets/zh.png')} />}
                        divider={divider}
                        fixed={true}
                        bgAnimate={true}
                        moveBgColor="255,255,255"
                        distance={100}
                        animateMove={this.handleMove}
                        right={<Link to="/cart" style={{ position: 'relative', top: '0.1rem' }}><Badge text={cartNum} overflowCount={9}>{anmation ? <img className="icon" src={require('../../assets/shop_h.png')} /> : <img className="icon" src={require('../../assets/shop.png')} />}</Badge></Link>}
                        animateEnd={this.handleAnimateEnd}
                    />
                    <div className="home_search" style={{ transform: `translateY(${Math.floor(-38 * val)}px) scale(${1 - 0.2 * val})` }}>
                        <Search
                            style={{ background: `${anmation ? ' #f4f4f4' : ''}` }}
                            defaultValue="您想要买什么呢~"
                            onFocus={this.handleMoveTo}
                        />
                    </div>

                </div>
                <div className="home_bg" />
                <div className="home_content">
                    <Carousel className="home_carouse" autoplay={true}>
                        {
                            carousels.map((item: any, index: number) => {
                                return (
                                    <Link to={`activity/${item.ad_type_id}`} key={index}>
                                        <div >
                                            <img src={item.image} />
                                        </div>
                                    </Link>
                                )
                            })
                        }
                    </Carousel>
                </div>
                <div className="home_hd">
                    <div className="home_hd_c">
                        <div className="home_hd_carouse">
                            <div style={{ transform: `translate(0, ${-top}rem)` }}>
                                {
                                    advert.map((item: any, index: number) => {
                                        return <Image src={item.image} key={index} />
                                    })
                                }
                            </div>
                        </div>
                    </div>
                    <Image src={require('../../assets/hd.gif')} />
                </div>
                <div className="home_content">

                    <Affix
                        style={{
                            zIndex: 9
                        }}
                        offsetTop={-160}
                        onChange={(affixed: boolean) => { this.setState({ affixed }) }}
                    >
                        {this.getGirdNode()}
                    </Affix>
                    <div className="grid list_ii">
                        {
                            hds.map((item: any, index: number) => {
                                return <Image src={item.image} key={index} />
                            })
                        }
                    </div>
                    <div className="grid list_new">
                        <div className="grid_title">新人必买 <span>NEW</span></div>
                        {
                            this.getNewPeople()
                        }
                    </div>
                    <div className="grid list_pep">
                        <div className="grid_title flex_justify">
                            <div className="flex">
                                <div className="flex_1">人气单品</div>
                                <div>
                                    <Button className="btn changeBtn" disabled={changeBtn} onClick={this.handleReValue}>
                                        <div>换一换
                                        <img className={loading ? 'rotate' : ''} src={require('../../assets/refash.png')} />
                                        </div>
                                    </Button>
                                </div>
                            </div>
                        </div>
                        <div className="flex grid_content">
                            {
                                popularity.map((item: any, index: number) => {
                                    return (
                                        <Link to={`/shopDetail/${item.id}`} className="flex_1 item_sp" key={index}>
                                            <div >
                                                <Image src={item.pic} />
                                                <Button className="btn">卖爆24.2万</Button>
                                                <div className="title flex_center">
                                                    <div className="flex">
                                                        <div
                                                            style={{
                                                                maxWidth: '4.25rem',
                                                                textOverflow: 'ellipsis',
                                                                whiteSpace: 'nowrap',
                                                                overflow: 'hidden'
                                                            }}
                                                        >
                                                            {item.name}
                                                        </div>
                                                        <img src={require('../../assets/arrow_right.png')} />
                                                    </div>
                                                </div>
                                            </div>
                                        </Link>
                                    )
                                })
                            }
                        </div>
                    </div>
                </div>
                <div className="gird list_hh">
                    <div className="gird_title">
                        好货特卖<span className="green">SALE</span>
                    </div>
                    <div className="gird_content flex" style={{ padding: '0 0.35rem' }}>
                        {
                            <div className="flex_1 item">
                                <div className="flex" style={{ marginTop: '0.725rem', marginLeft: '1.2rem' }}>
                                    <div className="qiangou">限时抢购</div>
                                    <div className="flex time">
                                        <Button className="btn">00</Button><span className="flex_justify">:</span><Button className="btn">30</Button><span className="flex_justify">:</span><Button className="btn">26</Button>
                                    </div>
                                </div>
                                <div className="jinping" style={{ marginLeft: '1.2rem' }}>精选好物  限时限量</div>
                                <div className="image flex">
                                    {
                                        quality.sale.goods.map((item: any, index: number) => {
                                            return (
                                                <Link to={`link/${item.id}`} className="flex_1" key={index}>
                                                    <div >
                                                        <Image src={item.pic} />
                                                        <Button className="btn_pro"><span>已抢65%</span></Button>
                                                        <div className="label">{item.price_q} 恒豆</div>
                                                    </div>
                                                </Link>
                                            )
                                        })
                                    }
                                </div>
                            </div>
                        }
                        {
                            <div className="flex_1 item">
                                <div className="flex" style={{ marginTop: '0.725rem', marginLeft: '1.2rem' }}>
                                    <div className="qiangou">新品上新</div>
                                </div>
                                <div className="jinping" style={{ marginLeft: '1.2rem' }}>品质好货 任您挑选</div>
                                <div className="image flex">
                                    {
                                        quality.new.map((item: any, index: number) => {
                                            return (
                                                <Link to={`/shopDetail/${item.id}`} className="flex_1" key={index}>
                                                    <div >
                                                        <Image src={item.pic} />
                                                        <Button className="btn_pro">已抢65%</Button>
                                                        <div className="label">{item.price_q} 恒豆</div>
                                                    </div>
                                                </Link>
                                            )
                                        })
                                    }
                                </div>
                            </div>
                        }

                    </div>
                </div>
                {
                    <div className="gird list_hh">
                        <div className="gird_title">
                            精选活动<span className="green">ACTIVITY</span>
                        </div>
                        <div className="gird_content">
                            <Image className="hdd" src={choice.act.image || ''} />
                        </div>
                    </div>
                }
                <div className="home_content_list">
                    <div className="hd_list flex">
                        {
                            choice.goods.map((item: any, index: number) => {
                                return (
                                    <Link to={`/shopDetail/${item.id}`} className="hd_list_item flex_1" key={index}>
                                        <div>
                                            <Image src={item.pic} />
                                            <div className="hd_list_item_title">{item.name}</div>
                                            <div className="hd_list_item_label">
                                                ¥ {item.price}+{item.price_q}
                                                <span>恒豆</span>
                                            </div>
                                        </div>
                                    </Link>
                                )
                            })
                        }
                    </div>
                    {!!live.length && <div className="gird list_hh">
                        <div className="gird_title">
                            猜您喜欢<span className="green">GUESS</span>
                        </div>
                        <div className="gird_content flex" style={{ flexFlow: 'wrap' }}>
                            {
                                live.map((item: any, index: number) => {
                                    return (
                                        <div className="live_item" key={index}>
                                            <div className="live_item_img">
                                                <Image src={item.pic} />
                                            </div>
                                            <div className="live_item_content">
                                                <div className="live_item_content_title">{item.name}</div>
                                                <div className="live_item_content_label">
                                                    ¥ {item.price}+{item.price_q}
                                                    <span>恒豆</span>
                                                </div>
                                            </div>
                                        </div>
                                    )
                                })
                            }
                        </div>
                    </div>}
                </div>
                <div className="end">
                    <img src={require('../../assets/end.png')} />
                    <div> 亲，已经看到最后啦</div>
                </div>
                <TabBarView select="home" />
                <ToTop />
            </div>
        )
    }

    public componentDidMount() {
        // window.addEventListener('touchstart', this.setInitValue)
        this.getData('indexapi/adsList', 'carousels', 1)
        this.getData('indexapi/cateList', 'classfy', 0)
        this.getData('indexapi/adslist', 'hds', 2)
        this.getData('indexapi/goodsale', 'quality')
        this.getData('indexapi/goodact', 'choice')
        this.getData('indexapi/goodhuman', 'popularity')
        this.getData('indexapi/adsList', 'newPeople', 5)
        this.getData('indexapi/goodGuessLike', 'live')
        this.getData('indexapi/adslist', 'advert', 6, () => {
            const { advert } = this.state
            let index = 0
            const setInval = () => {
                this.setState({
                    top: index * 3.4
                })
                if (index === advert.length - 1) {
                    index = 0
                } else {
                    index += 1
                }
            }
            this.timer = setInterval(setInval, 2000)
        })
        const { userInfo } = this.props
        if (userInfo.id) {
            post('indexapi/cartNumber', {
                userId: userInfo.id
            }).then((data: any) => {
                this.setState({
                    cartNum: data
                })
            })
        }
    }

    public componentWillUnmount() {
        clearInterval(this.timer)
        clearInterval(this.popularity)
    }

    private handleAnimateEnd = () => {
        this.setState({
            anmation: true,
            divider: true
        })
    }

    private handleReValue = () => {
        this.setState({
            loading: true,
            changeBtn: true,
        })
        this.popularity = setTimeout(
            () => {
                this.getData('indexapi/goodhuman', 'popularity').then(() => {
                    this.setState({ loading: false, changeBtn: false })
                })
            },
            2000
        )
    }

    private handleMove = (val: number) => {
        this.setState({
            val,
            anmation: false,
            divider: false
        })
    }

    private getNewPeople() {
        const { newPeople } = this.state
        const data = newPeople.map((item: any, index: number) => {
            return <Image src={item.image} key={index} />
        })
        return (
            <div className="flex grid_content">
                <div>
                    {data[0]}
                </div>
                <div className="right flex_1">
                    {data[1]}
                    {data[2]}
                </div>
            </div>
        )
    }

    private getGirdNode() {
        const { affixed, classfy } = this.state
        // const settings = {
        //     dots: false,
        //     infinite: false,
        //     focusOnSelect: true,
        //     speed: 500,
        //     arrows: false,
        //     slidesToShow: 1,
        //     slidesToScroll: 1,
        //     beforeChange: (oldIndex: number, newIndex: number) => {
        //         this.setState({
        //             index: newIndex + 1
        //         })
        //     }
        // }
        return (
            <div className="grid classfy">
                {/* <Slider {...settings} className="grid__carousel">
                    {
                        classfy.map((item: IClassfy, index: number) => {
                            if (index % 8 === 0) {
                                return (
                                    <div className="flex hidden grid_item"  key={index}>
                                        {<div onClick={() => { this.props.history.push('/category/?id=' + item.id) }}>
                                                <img src={item.icon} />
                                                <div className="text">{item.text}</div>
                                            </div>}
                                    </div>
                                )
                            }
                            return
                        })
                    }
                </Slider> */}
                {/* <GridView
                    data={classfy}
                    isCarousel={true}
                    activeStyle={false}
                    hasLine={false}
                    columnNum={5}
                    infinite={true}
                    className="grid__carousel"
                    onClick={(item: any) => { this.props.history.push('/category/?id=' + item.id) }}
                    itemStyle={{
                        padding: 0,
                        height: '4.3rem'
                    }}
                /> */}
                <Grid
                    className="grid__carousel"
                    data={classfy}
                    isCarousel={true}
                    columnNum={5}
                    dots={true}
                    infinite={true}
                    renderItem={(item: any, index: number) => {
                        return (
                            <Link to={`/category/?id=${item.id}`} key={index} >
                                <div>
                                    <img src={item.icon} />
                                    <div className="mk_grid_item_view__label">{item.name}</div>
                                </div>
                            </Link>
                        )
                    }}
                />
                {
                    affixed && (
                        <div className="flex hidden grid_item">
                            {
                                classfy.map((item: IClassfy, index: number) => {
                                    return (
                                        <div key={index} onClick={() => { this.props.history.push('/category/?id=' + item.id) }}>
                                            <img src={item.icon} />
                                            <div className="text">{item.text}</div>
                                        </div>
                                    )
                                })
                            }
                        </div>
                    )
                }
            </div >
        )
    }

    private handleMoveTo = () => {
        const { history } = this.props
        history.push('/search')
    }

    private async getData(uri: string, field: any, id?: number, callback?: () => void) {
        try {
            const { userInfo } = this.props
            const data: any = await post(uri, { id, userId: userInfo.id })
            if (uri === 'indexapi/cateList') {
                const imgs = data.map((i: any) => i.icon)
                const loading: PreLoad = new PreLoad(imgs)
                loading.success = () => {
                    this.setState({
                        [field]: data
                    })
                }
            } else {
                this.setState({
                    [field]: data
                })
            }
            if (isFunc(callback)) {
                callback()
            }
        } catch (e) {
            console.log(e)
        }
    }
}